<?php

namespace app\wechat\controller;

use app\model\CustomerChat;
use app\model\CustomerService;
use app\model\Members;
use app\model\Users;
use think\Controller;
use think\Config;
use app\model\Order;
use app\model\PayLog;
use EasyWeChat\Factory;
use think\Log;
use think\Session;

class PayController extends Controller
{
    protected $pay;
    protected $app;
    public function _initialize()
    {
        $this->app = Factory::officialAccount(Config::get('wechat'));
        $this->pay = Factory::payment(Config::get('pay'));
    }

    /**
     * 支付回调
     * @return mixed
     */
    public function payNotify()
    {
        $response = $this->pay->handlePaidNotify(function ($message, $fail) {
            $order = Order::get(['order_num' => $message['out_trade_no']]);
            if (!$order || ($order['status'])) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if (array_get($message, 'result_code') === 'SUCCESS') {
                    $order->status = '1';
                    $payLog = new PayLog();
                    $payLog->data([
                        'user_id' => $order['user_id'],
                        'order_id' => $order['id'],
                        'order_num' => $message['out_trade_no'],
                        'money' => $message['total_fee'] * 0.01,
                        'status' => '1',
                        'pay_time' => strtotime($message['time_end']),
                    ]);
                    $payLog->save();

                } elseif (array_get($message, 'result_code') === 'FAIL') {
                    $order->status = '0';
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            $order->save();
            return true;
        });

        return $response->send();
    }

    protected function sendTplMessage($openid, $nickname, $item_name, $order_id,$time,$member_name)
    {
        $params = [
            'touser' => $toopenid,
            'template_id' => 'MZWy9N-WNn5gSIoY1c7CR8GAY3_7X9C4FKLmEF6CU1w',
            'url' => 'http://gzh.tianxinyun.cn/admin/Order/edit?id=' . $order_id,
            'data' => [
                'first' => '您收到了一条新的订单',
                'tradeDateTime' => $time,
                'orderType' => $item_name,
                'customerInfo' => $nickname,
                'orderItemName' => '店员名称',
                'orderItemData' => $member_name,
                'remark' => '请立即处理'
            ]
        ];

        $res = $this->app->template_message->send($params);

        //记录日志
        $res['sendParams'] = $params;
        // 发送失败
        if ($res['errcode']) {
            Log::record($res, 'sendTplError');
            $result = sendMessage($openid, $nickname, $item_name, $order_id);
            return $result;
        } else {
            Log::record($res, 'sendTpl');
            return true;
        }
    }

}
